package 算法.leetcode.bytedance;

import 算法.leetcode.offer.base.ListNode;

/**
 * @author lchenglong
 * @date 2022/5/7
 */
public class OfferNode_III {

    public static void main(String[] args) {
        ListNode l1 =ListNode.init(new int[]{9,9,9,9,9,9,9});
        ListNode l2 =ListNode.init(new int[]{9,9,9,9});
        OfferNode_III instance = new OfferNode_III();
        ListNode ans = instance.addTwoNumbers(l1, l2);
        ListNode.print(ans);

    }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode vHead = new ListNode(-1);
        vHead.next = l1==null?l2:l1;
        ListNode cur = vHead.next,pre = vHead;
        int h = 0;
        while (cur!=null){
            int ln1 = l1==null?0:l1.val,ln2 =l2==null?0: l2.val;
            int data = ln1+ln2 +h;
            cur.val = data%10;
            h = data/10;
            l1 = l1==null?null:l1.next;
            l2 = l2==null?null:l2.next;
            if (cur.next == null){
                cur.next = l1==null?l2:l1;
            }
            cur = cur.next;
            pre = pre.next;
        }
        if (h==1){
            ListNode tail = new ListNode(1);
            pre.next = tail;
        }
        return vHead.next;
    }
}
